subroutine MC_ASM
    use asmcal
    use define
    use util_mc
    
    implicit none
    include "pspec.FI"
    include "mcbase.FI"
    include "mtbuf.FI"
    include "xsec.FI"
!$    include "omp_lib.h"
    
    integer :: batch, mi, iasm
    integer :: i, tid, nnt, base, nqtot
    integer :: nsource
    
    ! dummy for migration
    real(8) :: k_nn, ke 
    
    
    integer(8) :: bseed

    call initRN()
    bseed = gseed
    
    nq = nht_asm
    
    call init_asmcal
    swsplitting = 1
!    iasm=setupasm_nxt()
    iasm=setupasm_nxt()
    do while (iasm .ne. 0) 
        call initp_from_dist(nq, ntrn)
        k_nn=1.0_8
        ke = 0.0_8
        
        ! for inactive cycles
        do batch=1, inactcyc_asm
!$omp parallel private(mi,tid, nnt, base)&
!$omp default(shared)
!$    tid=omp_get_thread_num()+1
!$omp do
            do mi=1, nq
                call migrate(ntrn(mi), k_nn*swsplitting, ke*swsplitting, nnt, bseed, mi, &
                tid, psiomp(:,:,tid), jcomp(:,:,:,:,tid), gkomp(tid), ntrnomp(:,:,tid), nqomp(:,tid))
            enddo 
!$omp enddo

!$omp barrier
            base=sum(nqomp(OMPNXT,1:tid-1))
            do i=1, nqomp(OMPNXT,tid)
                ntrn(base+i)=ntrnomp(i,OMPNXT,tid)
            enddo
!$omp barrier

!$omp single
            bseed=strideN(bseed, nq)
            nq = sum(nqomp(OMPNXT,:))
            nqtot=nq
            nqomp(OMPNXT,:)=0

            gk=sum(gkomp)
!$omp end single

!$omp end parallel       
            k_nn=gk/nht_asm
            gk=0;gkomp=0
            print *, batch, "inactive for asm [",iasm,"]", "    k=", k_nn, nq
            call init_weight(nq, nht_asm, ntrn(:))
        enddo
        
        ! for active cycles
        call resetbuf_asmcal()
        do batch=1, actcyc_asm
            nsource=nq
!$omp parallel private(mi,tid, nnt, base)&
!$omp default(shared)
!$    tid=omp_get_thread_num()+1
!$omp do
            do mi=1, nq
                call migrate(ntrn(mi), k_nn*swsplitting, ke*swsplitting, nnt, bseed, mi, &
                tid, psiomp(:,:,tid), jcomp(:,:,:,:,tid), gkomp(tid), ntrnomp(:,:,tid), nqomp(:,tid))
            enddo 
!$omp enddo

!$omp barrier
            base=sum(nqomp(OMPNXT,1:tid-1))
            do i=1, nqomp(OMPNXT,tid)
                ntrn(base+i)=ntrnomp(i,OMPNXT,tid)
            enddo
!$omp barrier

!$omp single
            bseed=strideN(bseed, nq)
            nq = sum(nqomp(OMPNXT,:))
            nqtot=nq
            nqomp(OMPNXT,:)=0

            gk=sum(gkomp)
!$omp end single
!$omp end parallel            
            k_nn=gk/nht_asm
            gk=0;gkomp=0
            print *, batch, "  active for asm [",iasm,"]", "    k=", k_nn, nq
            call init_weight(nq, nht_asm, ntrn(:))
        enddo
        
        call homg_asm()
        
        iasm=setupasm_nxt()
    enddo
    
    call restore_core()
endsubroutine